package com.komorebi.friends.aop;

import com.komorebi.friends.constant.RedisConstant;
import com.komorebi.friends.model.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;

import static com.komorebi.friends.constant.UserConstant.USER_LOGIN_STATE;

/**
 * 请求响应日志 AOP
 *
 * @author <a href="暂无">komorebi</a>
 * @from <a href="https://yupi.icu">编程导航知识星球指导项目</a>
 **/
@Aspect
@Component
@Slf4j
public class RedisUserInfoInterceptor {

    @Resource
    StringRedisTemplate stringRedisTemplate;

    /**
     * 执行拦截
     */
    @Around("execution(* com.komorebi.friends.controller.*.*(..))")
    public Object doInterceptor(ProceedingJoinPoint point) throws Throwable {
        // 获取请求路径
        RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
        HttpServletRequest httpServletRequest = ((ServletRequestAttributes) requestAttributes).getRequest();
        //判断是否登录
        Object userObj = httpServletRequest.getSession().getAttribute(USER_LOGIN_STATE);
        User currentUser = (User) userObj;
        if (currentUser == null || currentUser.getId() == null) {
            //未登录
            return point.proceed();
        }
        //如果登录，则更新登录缓存时间
        String key = RedisConstant.REDIS_LOGIN_USERINFO_PREFIX + httpServletRequest.getSession().getId();
        //更新缓存时间
        stringRedisTemplate.expire(key,RedisConstant.LOGIN_USER_TTL, TimeUnit.MINUTES);
        return point.proceed();
    }
}

